import argparse
import yaml
import threading
from workers import frame_camera_worker,h264_camera_worker,alive_worker,detect_worker
from workers import notify_worker
from pathlib import Path
from tools.log import logger,setup_logger


def validate_file_path(path):
    """验证文件路径是否合法"""
    path = Path(path)
    if not path.exists():
        raise argparse.ArgumentTypeError(f"文件不存在: {path}")
    if not path.is_file():
        raise argparse.ArgumentTypeError(f"路径不是文件: {path}")
    return path

def validate_encoding(encoding):
    """验证编码格式是否有效"""
    try:
        "test".encode(encoding).decode(encoding)
        return encoding
    except LookupError:
        raise argparse.ArgumentTypeError(f"不支持的编码格式: {encoding}")

def parse_args():
    parser = argparse.ArgumentParser(
        formatter_class=argparse.ArgumentDefaultsHelpFormatter
    )
    
    parser.add_argument('--global_conf',
                       type=validate_file_path,
                       required=True,
                       help='全局配置文件路径 (必须存在)')
    
    parser.add_argument('--camera_conf',
                       type=validate_file_path,
                       required=True,
                       help='相机配置文件路径 (必须存在)')
    
    parser.add_argument('--conf_encoding',
                       type=validate_encoding,
                       default='utf-8',
                       help='文件编码格式')
    parser.add_argument('--log_file',
                       default=None,
                       help='日志文件')
    return parser.parse_args()

def load_conf(conf_path,conf_encoding):
    with open(conf_path,"r",encoding=conf_encoding) as file:
        return yaml.safe_load(file)    



if __name__=="__main__":
    
    args = parse_args()
    setup_logger(args.log_file)
    global_conf = load_conf(args.global_conf,args.conf_encoding)
    camera_conf = load_conf(args.camera_conf,args.conf_encoding)


    worker_list=[]
    worker_list.append(threading.Thread(target=detect_worker.work,args=(global_conf,camera_conf)))
    worker_list.append(threading.Thread(target=frame_camera_worker.work,args=(global_conf,camera_conf)))
    worker_list.append(threading.Thread(target=notify_worker.work,args=(global_conf,camera_conf)))
    # worker_list.append(threading.Thread(target=h264_camera_worker.work,args=(global_conf,camera_conf)))
    worker_list.append(threading.Thread(target=alive_worker.work,args=(global_conf,camera_conf)))

    for worker in worker_list:
        worker.start()
    logger.info("load_ok")
    for worker in worker_list:
        worker.join()
    